﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.Common.Dto.PrintTemplate;
using SHZY.BaseData.Interfaces.Common;
using SHZY.Systems.Entitys.System;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：打印模板.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "PrintTemplate", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBasePrintTemplateService : IComBasePrintTemplateService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBasePrintTemplateEntity> _repository;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBasePrintTemplateService"/>类型的新实例.
    /// </summary>
    public ComBasePrintTemplateService(
        ISqlSugarRepository<ComBasePrintTemplateEntity> wmsBasePrintTemplateRepository,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = wmsBasePrintTemplateRepository;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取打印模板.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBasePrintTemplateInfoOutput>();
    }

    /// <summary>
    /// 获取所有打印模板.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.EnCode).ToListAsync();
        return new { list = data.Adapt<List<ComBasePrintTemplateInfoOutput>>() };
    }

    /// <summary>
    /// 获取打印模板列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBasePrintTemplateListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<ComBasePrintTemplateEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.enCode), it => it.EnCode.Contains(input.enCode))
            .WhereIF(!string.IsNullOrEmpty(input.fullName), it => it.FullName.Contains(input.fullName))
            .WhereIF(!string.IsNullOrEmpty(input.type), it => it.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.EnCode.Contains(input.keyword) || it.FullName.Contains(input.keyword) || it.Type.Contains(input.keyword))
            .Where(it => it.DeleteMark == null)
            .Select(it => new ComBasePrintTemplateListOutput
            {
                id = it.Id,
                //type = it.Type,
                type = SqlFunc.Subqueryable<DictionaryDataEntity>().Where(d => d.EnCode.Equals(it.Type) && it.DeleteMark == null && d.DictionaryTypeId == "503736618222464645").Select(it => it.FullName),
                enCode = it.EnCode,
                fullName = it.FullName,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).MergeTable();
            //.OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id);
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.id);
        }
        var data=await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<ComBasePrintTemplateListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建打印模板.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBasePrintTemplateCrInput input)
    {
        if (await _repository.AnyAsync(x => (x.EnCode == input.enCode || x.FullName == input.fullName) && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrintTemplateEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新打印模板.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBasePrintTemplateUpInput input)
    {
        if (await _repository.AnyAsync(x => x.Id != input.id && (x.EnCode == input.enCode || x.FullName == input.fullName) && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrintTemplateEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除打印模板.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBasePrintTemplateEntity>().SetColumns(it => new ComBasePrintTemplateEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }
}